﻿#if UNITY_2019_4_OR_NEWER
#define UNITY_3D
#if UNITY_EDITOR
// 宏定义 THREAD_WORKERS_LIMITED 以限制 Thread Worker 数量最大为 4
//#define THREAD_WORKERS_LIMITED
#endif
using UnityEngine;
#endif
using System.Threading;

namespace Devil
{
    public class ThreadFlag
    {
        bool _abort;
        public bool IsAbort { get { return _abort; } }
        public bool IsVaild { get { return !_abort; } }

#if UNITY_EDITOR
        public string _name;
#endif

        public ThreadFlag(
#if UNITY_EDITOR
            string name = null
#endif
            )
        {
            _abort = false;

#if UNITY_EDITOR
            _name = name;
#endif
        }

        public void Start(WaitCallback callback)
        {
            if (!_abort)
            {
                _abort = !ThreadPool.QueueUserWorkItem(callback, this);
            }
#if UNITY_EDITOR
            if (_abort)
            {
                Debug.LogFormat("Don't start Thread. \"{0}\"", this);
            }
#endif
        }

        public void Abort()
        {
#if UNITY_EDITOR
            if (!_abort && !string.IsNullOrEmpty(_name))
                Debug.LogFormat("Abort Thread ({0})", this);
#endif
            _abort = true;
        }

#if UNITY_EDITOR
        public override string ToString()
        {
            return string.Format("ThreadFlag({0:x}:{1} {2})", GetHashCode(), _name, IsAbort ? " ,abort" : "");
        }
#endif
    }

}